package com.lyf.core.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lyf.core.R;
import com.lyf.core.presenter.view.BaseView;
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity<VB extends ViewBinding> extends RxAppCompatActivity implements BaseView, EasyPermissions.PermissionCallbacks {

    //等待进度框
    private LoadingPopupView mProgressDialog;
    protected VB mViewBinding;
    public static final int OPEN_GPS_REQUEST_CODE = 9999;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    public Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar();
        //设置竖屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mViewBinding = getViewBinding();
        setContentView(mViewBinding.getRoot());
        if (isRegisterEvent()) {
            EventBus.getDefault().register(this);
        }
        mContext = this;
        init();
        initEvent();
    }

    protected void initStatusBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
    }

    protected abstract VB getViewBinding();


    protected boolean isCheckOpenGps() {
        return false;
    }

    protected boolean isRegisterEvent() {
        return false;
    }

    protected boolean isBackExitApp() {
        return false;
    }

    protected void init() {

    }

    protected void initEvent() {

    }

    @Override
    public void showLoading() {
        runOnUiThread(() -> creLoading(""));
    }

    @Override
    public void showLoading(String title) {
        runOnUiThread(() -> creLoading(title));
    }


    private void creLoading(String title) {
        if (isFinishing()) {
            return;
        }

        if (mProgressDialog != null && mProgressDialog.isShow()) {
            return;
        }
        mProgressDialog = new LoadingPopupView(this, 0);

        if (!TextUtils.isEmpty(title)) {
            mProgressDialog.setTitle(title);
        }

        BasePopupView dialog = new XPopup.Builder(this)
                .autoOpenSoftInput(false)
                .isDestroyOnDismiss(true)
                .hasShadowBg(false)
                .isRequestFocus(false)
                .dismissOnTouchOutside(false)
                .asCustom(mProgressDialog)
                .show();
        //解决部分手机弹窗键盘弹出后收回 与上面的isRequestFocus 配合使用
        dialog.popupInfo.isRequestFocus = true;
    }

    private void dismissLoading() {
        if (isFinishing()) {
            return;
        }
        if (mProgressDialog != null && mProgressDialog.isShow()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    public void stopLoading() {
        runOnUiThread(() -> dismissLoading());
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void showMessage(int message) {
        ToastUtils.showShort(message);
    }

    //权限请求码
    public static final int RC_PERMISSION_CODE = 98;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限申请失败 提示转到设置界面手动打开
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.e("onPermissionsDenied", "BaseActivity  -------------------onPermissionsDenied: ");
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle(getString(R.string.permisssion_title_settings_dialog))
                    .setPositiveButton(getString(R.string.permission_button_setting))
                    .setNegativeButton(getString(R.string.permission_button_cancle))
                    .setRequestCode(RC_PERMISSION_CODE)
                    .build()
                    .show();
        }
    }

    /**
     * 权限申请成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }


    @Override
    protected void onDestroy() {
        dismissLoading();
        mViewBinding = null;
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    /**
     * activity动画的设置
     */

    public void startActivityByLeft(Intent intent) {
        startActivity(intent);
        overridePendingTransition(R.anim.aim_common_right_in,
                R.anim.aim_common_left_out);
    }

    @Override
    public void onBackPressed() {
        if (!isBackExitApp()) {
            super.onBackPressed();
        } else {
            if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                ActivityUtils.finishAllActivities();
                AppUtils.exitApp();
            } else {
                TOUCH_TIME = System.currentTimeMillis();
                showMessage(StringUtils.getString(R.string.exit_application));
            }

        }
    }
}
